package com.example.demo.controller;

import com.example.demo.util.TableUtil;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.Pagination;
import javafx.scene.control.TableView;
import javafx.util.Callback;
import lombok.Getter;
import lombok.Setter;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @Author hweiyu
 * @Description
 * @Date 2022/6/23 17:44
 */
public class TableController implements Initializable {

    @FXML
    @Getter
    private TableView<?> table;

    @FXML
    private Pagination pagination;

    @Setter
    private Integer pageSize = 10;

    private boolean isDoPageCallback = false;

    public Integer getPageNo() {
        return pagination.getCurrentPageIndex() + 1;
    }

    public void setPageNo(Integer pageNo) {
        pagination.setCurrentPageIndex(pageNo);
    }

    public Integer getPageSize() {
        return pageSize;
    }

    private Callback<Integer, Node> pageFactory = pageNo -> {
        //防止操作Page对象时，会多次调用此方法
        if (isDoPageCallback) {
            //将已选中中checkbox取消选中状态
            getTable().refresh();
            doPageCallback();
        }
        return new Label(String.valueOf(pageNo));
    };

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //初始化分页
        TableUtil.initPage(pagination, pageFactory);
        TableUtil.initTable(table);

        doInit();
    }

    public void doInit() {}

    public void refreshTable() {}

    /**
     * 点击页码时触发的回调
     */
    public void doPageCallback() {

    }

    public void renderPage(long total, List<?> records) {
        TableUtil.setData(table, records);
        isDoPageCallback = false;
        //设置总页码
        pagination.setPageCount((int) (total / 10 + (total % 10 == 0 ? 0 : 1)));
        isDoPageCallback = true;
    }
}
